export default {
  ADDGoods(state, data) {
    const datas = { // 传入的商品属性
      cp_name: data.cp_name,
      imgurl: data.imgurl,
      num: 1,
      price: data.price,
      mssage: data.mssage,
      selected: false,
      cp_id: data.cp_id
    }
    let index = -1
    index = state.car.findIndex(item => { // 返回元素的索引位置，如果没有符合条件的元素返回 -1
      return item.cp_id === data.cp_id
    })
    if (index === -1) { // 返回-1说明购物车里没有这个商品，则push进去，如果返回下标，则让此商品的数量加1
      state.car.push(datas)
    } else {
      state.car[index].num++
    }
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  // 购物车页面数量加减
  ADDNUM(state, cpid) {
    const index = state.car.findIndex(item => {
      return item.cp_id === cpid
    })
    return state.car[index].num++
  },
  // 购物车页面数量加减
  JIANNUM(state, cpid) {
    const index = state.car.findIndex(item => {
      return item.cp_id === cpid
    })
    if (state.car[index].num === 0) {
      state.car[index].selected = true
      var list = []
      state.car.forEach((item, index) => {
        if (!item.selected) {
          list.push(item)
        }
      })
      return (state.car = list)
    } else {
      state.car[index].num--
    }
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  deleteStoreCart(state, cpid) {
    state.car.some((item, index) => {
      if (item.cp_id === cpid) {
        state.car.splice(index, 1)
      }
    })
    localStorage.setItem('car', JSON.stringify(state.car))
  },
  ClearCar(state, data) {
    state.car = []
  }
}
